import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.tree.*;

/** Structure du patch
  *
  * @author     Nemesis (nemesis_tt@yahoo.fr)
  * @version    08/05/04
  */

public class Structure extends JPanel {

// Les éléments de la vue (IHM)
// ----------------------------
        
    /** Arbre d'affichage */
    private JTree arbre;
    
    /** Modifs associées */
    private Modif modif;

// Le constructeur
// ---------------

    /** Construire le panel de représentation du patch */
    public Structure(Patch patch) {
        super();
        
        //  Définition du layout de la zone
        setLayout(new BorderLayout());
        
        // Arbre représentant le patch
        modif = patch.getModifs();
        arbre = new JTree(modif);
        arbre.setCellRenderer(new CheckRenderer());
        arbre.getSelectionModel().setSelectionMode(
            TreeSelectionModel.SINGLE_TREE_SELECTION);
        arbre.putClientProperty("JTree.lineStyle", "Angled");
        arbre.addMouseListener(new NodeSelectionListener(arbre));
        
        // Gestion du défilement
        JScrollPane scroll = new JScrollPane(arbre);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        
        // Ajout final de l'élement
        add(scroll);
    }
    
    class NodeSelectionListener extends MouseAdapter {
        JTree tree;
        
        NodeSelectionListener(JTree tree) {
            this.tree = tree;
        }
        
        public void mouseClicked(MouseEvent e) {
            int x = e.getX();
            int y = e.getY();
            int row = tree.getRowForLocation(x, y);
            TreePath path = tree.getPathForRow(row);
            
            if (path != null) {
                CheckNode node = (CheckNode)path.getLastPathComponent();
                boolean isSelected = ! (node.isSelected());
                node.setSelected(isSelected);
                if (node.getSelectionMode() == CheckNode.DIG_IN_SELECTION) {
                    if ( isSelected ) {
                        tree.expandPath(path);
                    } else {
                        tree.collapsePath(path);
                    }
                }
                ((DefaultTreeModel)tree.getModel()).nodeChanged(node);
                if (row == 0) {
                    tree.revalidate();
                    tree.repaint();
                }
            }
        }
    }
}
